package com.ayz.gateway.core.datasource.connection;


import com.ayz.gateway.core.datasource.Connection;
import com.ayz.gateway.core.datasource.RpcStatement;
import com.ayz.gateway.core.rpc.IGatewayApi;
import com.ayz.gateway.core.rpc.config.DubboConfiguration;
import com.ayz.gateway.core.rpc.utils.NamingGenerator;
import lombok.Data;


/**
 * @ClassName DubboConnection
 * @Description TODO: Dubbo作为RPC通信框架
 * @Author 快乐的星球
 * @Date 2023/5/9 11:00
 * @Version 1.0
 **/
@Data
public class DubboConnection implements Connection {
    /**
     * 使用Dubbo作为通信框架下全局上下文的配置项参数
     */
    private DubboConfiguration dubboConfiguration;

    public DubboConnection(DubboConfiguration dubboConfiguration) {
        this.dubboConfiguration = dubboConfiguration;
    }

    @Override
    public Object execute(RpcStatement rpcStatement) throws Exception {
        //1: 获取RPC唯一资源名称
        String rpcResource= NamingGenerator.generateRpcResourceName(rpcStatement.getApplicationName(),
                rpcStatement.getInterfaceName(),rpcStatement.getMethodName());
        //2:获取泛化资源代理对象
        IGatewayApi iGatewayApi = dubboConfiguration.getGenericReference(rpcResource);
        //3:获取同步还是异步调用
        boolean sync = rpcStatement.isSync();
        if(sync){
            //同步调用
            return iGatewayApi.callSync(rpcStatement.getArgs(),rpcStatement.getParameterTypeNames());
        }else {
            //异步调用
            return iGatewayApi.callAsync(rpcStatement.getArgs(), rpcStatement.getParameterTypeNames());
        }
    }
}
